// pages/news/imgSubmit.js
import ImgListCell from '../../template/ImgListCell';
const util = require('../../utils/util.js');
const apiUrl = require('../../utils/apiUrl.js');
var http = require('../../utils/httpHelper.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    winWidth: 0,
    winHeight: 0,
    id: 0,
    detail: {},
    newsTitle: "",
    latitude: 0,
    longitude: 0,
    position: "",
    videoSrc: "",
    showType: 2,
    copyfrom: "",
    editor: "",
    relID: 0,
    sourceType: 0,
    sourceAuthor: "",
    sourceUID: 0,
    loaddinghidden: true,
    formats: {},
    keyboardHeight: 0,
    isIOS: false,
    showLoading: false,
    columnIndex: 0,
    columnID: 0,
    columnArray: [],
    columnNameArray: [],
    imageArray: [],
    imgsList: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this
    var id = options.id;
    if (id) {
      that.setData({
        id: id
      })
      wx.setNavigationBarTitle({
        title: '编辑文章',
      })
      that.loadData();
    } else {
      that.loadColumnData();
    }

    // 运行时检查定位接口可用性与授权
    this.checkLocationAvailability(false, function (ok) {
      if (!ok) return;
      wx.getLocation({
        type: 'wgs84',
        success: function (res) {
          var latitude = res.latitude
          var longitude = res.longitude

          // console.log("latitude:" + latitude);
          // console.log("longitude:" + longitude);

          wx.setStorageSync("latitude", latitude);
          wx.setStorageSync("longitude", longitude);

          that.setData({
            latitude: latitude,
            longitude: longitude
          });

        },
        fail: function (err) {
          console.log("err:" + err);
        }
      })
    });

    /**
     * 获取系统信息
     */
    wx.getSystemInfo({

      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });
  },
  loadColumnData: function () {
    var that = this;

    var parameter = {};
    parameter['all'] = 0;
    //获取数据
    http.ApiGet(apiUrl.UrlColumnTree, parameter, function (res) {
      wx.stopPullDownRefresh() //停止下拉刷新
      if (res.code == 1) {
        var newData = res.data;
        if (newData.length > 0) {
          var columnName = [];
          var columnIndex = 0;
          var columnID = newData[0].id;

          //编辑时加载的栏目id
          if (that.data.detail.column_id) {
            columnID = that.data.detail.column_id;
          }

          newData.map(function (item, index) {
            columnName.push(item.text);
            if (columnID == item.id) {
              columnIndex = index;
            }
          });
          that.setData({
            columnArray: newData,
            columnNameArray: columnName,
            columnID: columnID,
            columnIndex: columnIndex
          });
        }
      }
    });
  },
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    var columnArray = this.data.columnArray;
    this.setData({
      columnIndex: e.detail.value,
      columnID: columnArray[e.detail.value].id
    })
  },
  chooseLocation: function () {
    var that = this;
    var latitude = wx.getStorageSync("latitude");
    var longitude = wx.getStorageSync("longitude");
    this.checkLocationAvailability(true, function (ok) {
      if (!ok) return;
      wx.chooseLocation({
        latitude: latitude,
        longitude: longitude,
        success(res) {
          console.log(res);
          that.setData({
            latitude: res.latitude,
            longitude: res.longitude,
            position: res.address,
          });
        },
        fail(err) {
          console.log('chooseLocation fail:', err);
        }
      });
    });
  },
  loadData: function () {
    var that = this;
    var parameter = {};
    parameter['id'] = that.data.id;

    http.ApiGet(apiUrl.UrlNewsDetail, parameter, function (res) {
      if (res.code == 1) {

        var imgsList = [];
        var imgList = res.data.imgList;
        for (var i = 0; i < imgList.length; i++) {
          var theitem = imgList[i];
          var item = {};
          item["imgsrc"] = theitem["image_url"];
          item["intor"] = theitem["image_intor"];
          imgsList.push(item);
        }

        that.setData({
          loaddinghidden: true,
          newsTitle: res.data.title,
          imageArray: res.data.images,
          columnID: res.data.column_id,
          detail: res.data,
          videoSrc: res.data.video_url,
          showType: res.data.show_type,
          position: res.data.position,
          copyfrom: res.data.copyfrom,
          editor: res.data.editor,
          relID: res.data.rel_id,
          sourceType: res.data.source_type,
          sourceAuthor: res.data.source_author,
          sourceUID: res.data.source_uid,
          imgsList: imgsList
        });
        console.log("loadData");
        that.loadColumnData();
      } else {
        wx.showModal({
          title: res.msg
        });
      }
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  formSubmit: function (e) {

    var that = this;

    var formData = e.detail.value;


    var draft = e.detail.target.dataset.draft;
    formData["is_draft"] = draft;

    if (formData.title == "") {
      wx.showModal({
        title: '请填写标题',
      });
      return;
    }

    var columnID = that.data.columnID;
    if (columnID > 0) {
      formData["column_id"] = columnID;
    } else {
      wx.showModal({
        title: '请选择栏目',
      });
      return;
    }

    //封面
    var imageArray = that.data.imageArray;
    var imgStr = "";
    if (imageArray.length > 0) {
      imgStr = imageArray[0];
      if (imageArray.length > 1) {
        for (let j = 1; j < imageArray.length; ++j) {
          imgStr += "," + imageArray[j];
        }
      }
    }
    formData["cover"] = imgStr;


    formData["copyfrom"] = that.data.copyfrom;
    formData["editor"] = that.data.editor;
    var showType = that.data.showType;

    var videoSrc = that.data.videoSrc;
    if (videoSrc.length > 0) {
      formData["video_url"] = videoSrc;
      // showType = 3;
    }


    var imgsList = that.data.imgsList;
    var imgsListStr = "";
    var intorStr = "";
    if (imgsList.length > 0) {
      imgsListStr = imgsList[0]["imgsrc"];
      intorStr = imgsList[0]["intor"];

      if (imgsList.length > 1) {
        for (let j = 1; j < imgsList.length; ++j) {
          imgsListStr += "," + imgsList[j]["imgsrc"];
          intorStr += "|||" + imgsList[j]["intor"];
        }
      }
    }
    formData["imgList"] = imgsListStr;
    formData["image_intor"] = intorStr;
    showType = 2;

    formData["show_type"] = showType;

    formData["position"] = that.data.position;

    var longitude = that.data.longitude;
    if (longitude > 0) {
      formData["longitude"] = longitude;
    }
    var latitude = that.data.latitude;
    if (latitude > 0) {
      formData["latitude"] = latitude;
    }

    formData["rel_id"] = that.data.relID;
    formData["source_type"] = that.data.sourceType;
    formData["source_author"] = that.data.sourceAuthor;
    formData["source_uid"] = that.data.sourceUID;

    // console.log(formData);
    // return;

    // formData["content"] = "";
    that.submitPost(formData);

  },
  submitPost(formData) {
    var that = this;

    console.log(formData);
    wx.showToast({
      title: '正在提交',
      icon: 'loading',
      duration: 2000,
      mask: true,
    });

    var url = apiUrl.UrlNewsAdd;
    if (that.data.id > 0) {
      url = apiUrl.UrlNewsEdit;
      formData["news_id"] = that.data.id;
    }

    http.ApiPost(url, formData, function (res) {
      if (res.code == 1) {
        wx.showToast({
          title: '提交成功！',
          icon: 'success',
          duration: 2000
        });
        wx.navigateBack();
      } else {
        wx.showModal({
          title: res.msg
        });
      }
    });
  },
  chooseImage: function () {
    const that = this;
    var count = that.data.imageArray.length;
    count = 3 - count;

    if (count > 0) {
      wx.chooseImage({
        count: count,
        success: function (res) {
          for (let j = 0; j < res.tempFilePaths.length; ++j) {
            that.uploadImage(res.tempFilePaths[j], 0, 0)
          }
        }
      })
    } else {
      wx.showModal({
        title: '封面图不能超过三张！'
      });
    }

  },
  uploadImage: function (path, type, index) {
    var that = this
    that.showLoading();
    var postData = {};
    var user = wx.getStorageSync("user");
    if (user) {
      postData['appid'] = user.appid;
      postData['min_app'] = 1;
      wx.uploadFile({
        url: apiUrl.UrlUploadImg,
        filePath: path,
        name: 'file',
        formData: postData,
        success: function (res) {
          that.cancelLoading();
          var result = JSON.parse(res.data)
          // console.log(result);
          if (result.code == 1) {
            wx.hideToast();

            if (type == 1) {

              var item = {};
              item["imgsrc"] = result.data.url;
              item["intor"] = "";

              that.setData({
                imgsList: that.data.imgsList.concat(item),
              })

            } else if (type == 2) {
              var imgsList = that.data.imgsList;
              imgsList[index]["imgsrc"] = result.data.url;

              that.setData({
                imgsList: imgsList,
              })
            } else {
              that.setData({
                imageArray: that.data.imageArray.concat(result.data.url),
              })
            }
          } else {
            wx.showModal({
              title: result.msg
            });
          }
        },
        fail: function (err) {
          console.log(err);
          that.cancelLoading();
          wx.showModal({
            title: '上传出错！'
          });
        }
      })
    }
  },
  delImg: function (e) {
    var that = this;
    var index = e.target.dataset.index;
    wx.showModal({
      title: '确定删除？',
      success: function (res) {
        if (res.confirm) {
          var imageArray = that.data.imageArray;
          imageArray.splice(index, 1);
          that.setData({
            imageArray: imageArray
          })
        }
      }
    })
  },
  showLoading: function () {
    this.setData({
      showLoading: true
    })
  },
  cancelLoading: function () {
    this.setData({
      showLoading: false
    })
  },
  addImgsTap: function () {
    const that = this;
    wx.chooseImage({
      count: 9,
      success: function (res) {
        for (let j = 0; j < res.tempFilePaths.length; ++j) {
          that.uploadImage(res.tempFilePaths[j], 1, 0);
        }
      }
    })
  },
  intorInput: function (e) {
    const that = this;
    var index = e.target.dataset.index;

    var imgsList = that.data.imgsList;
    imgsList[index]["intor"] = e.detail.value;

    that.setData({
      imgsList: imgsList,
    })
  },
  changeImage: function (e) {
    const that = this;
    var index = e.target.dataset.index;
    // console.log(index);
    wx.chooseImage({
      count: 1,
      success: function (res) {
        for (let j = 0; j < res.tempFilePaths.length; ++j) {
          that.uploadImage(res.tempFilePaths[j], 2, index);
        }
      }
    })

  },
  delImgs: function (e) {
    var that = this;
    var index = e.target.dataset.index;
    wx.showModal({
      title: '确定删除？',
      success: function (res) {
        if (res.confirm) {
          var imgsList = that.data.imgsList;

          imgsList.splice(index, 1);

          that.setData({
            imgsList: imgsList
          })
        }
      }
    })
  },
})